package it.uniparthenope.smartqueue;

import static it.uniparthenope.smartqueue.CommonUtilities.DISPLAY_MESSAGE_ACTION;
import static it.uniparthenope.smartqueue.CommonUtilities.EXTRA_MESSAGE;
import static it.uniparthenope.smartqueue.CommonUtilities.SENDER_ID;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

//import com.androidhive.pushnotifications.R;
import com.google.android.gcm.GCMRegistrar;

public class MainActivity extends Activity {
	// label to display gcm messages
	TextView lblMessage;
	
	TextView numero;
	TextView myNum;
	
	
	// Asyntask
	AsyncTask<Void, Void, Void> mRegisterTask;
	
	// Alert dialog manager
	AlertDialogManager alert = new AlertDialogManager();
	
	// Connection detector
	ConnectionDetector cd;
	
	public static String name;
	public static String email;
	public static int currNumber;
	
	public boolean restart=false;
	
	
	
	@Override
	protected void onResume() {
		super.onResume();
		if (restart) {
			Intent register = new Intent(this,RegisterActivity.class);
			startActivity(register);
		}
	}
	
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
	    
		/*
		cd = new ConnectionDetector(getApplicationContext());

		// Check if Internet present
		if (!cd.isConnectingToInternet()) {
			// Internet Connection is not present
			alert.showAlertDialog(MainActivity.this,
					"Nessuna connessione ad Internet",
					"Connetti prima ad una rete", false);
			// stop executing code by return
			Intent refresh = new Intent(this,MainActivity.class);
			startActivity(refresh);
		}
		*/
		
		// Getting name, email from intent
		Intent i = getIntent();
		
		name = i.getStringExtra("name");
		//User.myNumber = name;
		email = i.getStringExtra("email");		
		
		// Make sure the device has the proper dependencies.
		GCMRegistrar.checkDevice(this);

		// Make sure the manifest was properly set - comment out this line
		// while developing the app, then uncomment it when it's ready.
		GCMRegistrar.checkManifest(this);

		lblMessage = (TextView) findViewById(R.id.lblMessage);
		
		registerReceiver(mHandleMessageReceiver, new IntentFilter(
				DISPLAY_MESSAGE_ACTION));
		
		// Get GCM registration id
		final String regId = GCMRegistrar.getRegistrationId(this);

		// Check if regid already presents
		if (regId.equals("")) {
			// Registration is not present, register now with GCM			
			GCMRegistrar.register(this, SENDER_ID);
			
			// stampa subito i dati
			printData();
			
			
		} else {
			// Device is already registered on GCM
			if (GCMRegistrar.isRegisteredOnServer(this)) {
				// Skips registration.				
			//	Toast.makeText(getApplicationContext(), "Already registered with GCM", Toast.LENGTH_LONG).show();
			} else {
				// Try to register again, but not in the UI thread.
				// It's also necessary to cancel the thread onDestroy(),
				// hence the use of AsyncTask instead of a raw thread.
				final Context context = this;
				mRegisterTask = new AsyncTask<Void, Void, Void>() {

					@Override
					protected Void doInBackground(Void... params) {
						// Register on our server
						// On server creates a new user
						ServerUtilities.register(context, name, email, regId);
						return null;
					}

					@Override
					protected void onPostExecute(Void result) {
						mRegisterTask = null;
					}

				};
				mRegisterTask.execute(null, null, null);
			}
		}
		
		
	}		

	/**
	 * Receiving push messages
	 * */
	private final BroadcastReceiver mHandleMessageReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			String newMessage = intent.getExtras().getString(EXTRA_MESSAGE);
			// Waking up mobile if it is sleeping
			WakeLocker.acquire(getApplicationContext());
			
			/**
			 * Take appropriate action on this message
			 * depending upon your app requirement
			 * For now i am just displaying it on the screen
			 * */
			
			// Showing received message
			//lblMessage.append(newMessage + "\n");			
			//Toast.makeText(getApplicationContext(), "New Message: " + newMessage, Toast.LENGTH_LONG).show();
			
			
			// aggiorna i dati
			printData();
				
			// Releasing wake lock
			WakeLocker.release();
		}
	};
	
	@Override
	protected void onDestroy() {
		if (mRegisterTask != null) {
			mRegisterTask.cancel(true);
		}
		try {
			unregisterReceiver(mHandleMessageReceiver);
			GCMRegistrar.onDestroy(this);
			
		} catch (Exception e) {
			Log.e("UnRegister Receiver Error", "> " + e.getMessage());
		}
		super.onDestroy();
	}
	
	
	
	// cancella iscrizione
	public void unlink (){
		//Toast.makeText(this, "" + GCMIntentService.regId ,Toast.LENGTH_SHORT).show();
		GCMRegistrar.unregister(this);
		/*
		try{
		String URL = "http://students.uniparthenope.it/~0124000315/progetti/gcm_server_php/delete.php?mail=" + email;
		HttpClient httpclient = new DefaultHttpClient();
	    HttpResponse response = httpclient.execute(new HttpGet(URL));
	    StatusLine statusLine = response.getStatusLine();
	    if(statusLine.getStatusCode() == HttpStatus.SC_OK){
	        ByteArrayOutputStream out = new ByteArrayOutputStream();
	        response.getEntity().writeTo(out);
	        out.close();
	        String responseString = out.toString();
	        //..more logic
	    } else{
	        //Closes the connection.
	        response.getEntity().getContent().close();
	        throw new IOException(statusLine.getReasonPhrase());
	    }
		}
		catch (Exception e){}
		*/
		restart = true;
		this.moveTaskToBack(true);
	}
	

	
	
	
 public int getNumber () {
	 String url = "http://students.uniparthenope.it/~0124000315/progetti/gcm_server_php/getNumber.json";
	 String json = CommonUtilities.readJSON(url);
	 String num = "";
	 try {
		 JSONObject obj = new JSONObject (json);
		 num = obj.getString("numero");
	 }
	 catch (Exception e) {}
	 
	 return Integer.parseInt(num);
 }
 
 
 public void printData() {
	 
	// prende il numero corrente e lo stampa
				currNumber = getNumber();
			 
				if (Integer.parseInt(name) == currNumber) {
					AlertDialog.Builder miaAlert = new AlertDialog.Builder(this);
					miaAlert.setMessage("L' applicazione verra' ora chiusa");
					miaAlert.setTitle("E' arrivato il tuo turno.");

					miaAlert.setCancelable(false);
					miaAlert.setPositiveButton("Chiudi", new DialogInterface.OnClickListener() {
					  public void onClick(DialogInterface dialog, int id) {
						unlink();
					  }
					});
					    	
					
					AlertDialog alert = miaAlert.create();
					alert.show();
					;
				}
					
				
				numero = (TextView) findViewById (R.id.corrente);
				myNum = (TextView) findViewById (R.id.mioNumero);
				
				numero.setText(" " + currNumber);
				myNum.setText ("Il tuo numero : " + name);
				
				
 }
	 
}


